# -*- coding: utf-8 -*-
# Author: xiantingDeng
# File: devices.py
# Time: 9:12

import sys

import allure
from airtest.core.android.android import *
from airtest.core.api import *
from common.util.api_util import devices
from common.util.env_util import EnvironmentConfiguration


class OriginalEquipment():
    def __init__(self, log):
        self.__log = log
        self.equipment = devices()[0]
        self.apppackage = EnvironmentConfiguration().get_apppackage_version()[1]
        self.apk_path = EnvironmentConfiguration().get_app_file_path()
    def connecting_device(self):
        '''
        连接设备
        :return: TRUE Flase
        '''
        with allure.step("连接设备：{}".format(self.equipment)):
            try:
                connect_device("android:///" + self.equipment)
                self.__log.info("连接{}设备成功，开始执行响应的操作。".format(self.equipment))
                return True
            except Exception as e:
                self.__log.error("设备连接失败：{}".format(e))
                return False

    def wheter_install_app(self):
        '''
        判断是否安装对应的APP
        :return: TRUE Flase
        '''
        with allure.step("判断是否安装APK文件"):
            try:
                if self.connecting_device():
                    command = "adb -s {} shell pm list package".format(self.equipment)
                    commandresult = os.popen(command).read()
                    if "package:" + self.apppackage in commandresult:
                        return True
                    else:
                        return False
            except Exception as e:
                self.__log.error("判断安装出现异常：{}".format(e))

    def Uninstall_and_reinstall(self):
        '''
        先判断是否安装应用，如已安装则卸载重新安装，否则直接安装
        :return:
        '''
        with allure.step("卸载重新安装APP"):
            try:
                if self.wheter_install_app():
                    uninstallmmand = f"adb -s {self.equipment} uninstall {self.apppackage}"
                    self.__log.info("该设备已安装：{}".format(self.apppackage))
                    self.__log.info("正在对{}设备卸载{}，卸载命令为：{}".format(self.equipment, self.apppackage, uninstallmmand))
                    os.popen(uninstallmmand)
                else:
                    self.__log.info("设备{}未安装{}，开始进行安装".format(self.equipment, self.apppackage))
                time.sleep(4)
                installmmand = f"adb -s {self.equipment} install -r {self.apk_path}"
                self.__log.info("正在对{}设备安装{}，安装命令为：{}".format(self.equipment, self.apppackage, installmmand))
                os.popen(installmmand)

                time.sleep(10)
                if self.wheter_install_app():
                    self.__log.info("{}设备已安装{}成功".format(self.equipment, self.apppackage))
                    return True
                else:
                    self.__log.info("{}设备安装{}失败".format(self.equipment, self.apppackage))
                    return False
            except Exception as e:
                self.__log.error("安装异常：{}".format(e))

    def open_the_installation(self):
        '''打开APP'''
        with allure.step("打开APP"):
            try:
                if self.Uninstall_and_reinstall():
                    start_app(self.apppackage)
                    self.__log.info("打开APP成功，开始执行相关操作！")
                    return True
                else:
                    self.__log.warning("打开APP失败，未完成APP的安装")
                    return False
            except Exception as e:
                self.__log.error("打开APP出现异常：{}".format(e))

    def get_sccreen_size(self):
        '''获取屏幕大小'''
        size_strs = f"adb -s {self.equipment} shell wm size "
        size_str = os.popen(size_strs).read()
        if not size_str:
            self.__log.warning("请安装ADB及驱动并配置环境变量")
            sys.exit()
        size = re.search(r'(\d+)x(\d+)', size_str)
        height = size.group(2)
        width = size.group(1)
        return int(width), int(height)


if __name__ == '__main__':
    from common.util.log_util import GenerateLog
    OriginalEquipment(GenerateLog().logger()).open_the_installation()